package com.daocao.hua.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.R;
import com.daocao.hua.api.bean.UploadSubmitIdcardBean;
import com.daocao.hua.api.callback.AutonymContract;
import com.daocao.hua.api.requestInfo.AutonymRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.IdCardBitmap;
import com.daocao.hua.model.IdentityModel;
import com.daocao.hua.model.ResponseModel;
import com.daocao.hua.util.ImageUtil;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.CircularProgress;
import com.daocao.hua.view.Dialog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 实名认证界面
 * Created by Master.Dong on 16/4/10.
 */
public class AutonymActivity extends PermissionActivity implements View.OnClickListener, AutonymContract.View {

    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    //    private static final String DEFAULT_PATH = "/sdcard/pictures";
//    private static final String DEFAULT_TYPE = "idcard";
    //    private Bitmap backBit;
//    private File backFile;
    private ImageView backIv;
    private int btnId;
    //    private Bitmap frontBit;
    private ImageView frontIv;
    private boolean isTakeOne;
    private boolean isTakeTwo;
    private CircularProgress loading;
    private boolean oneUpload;
    private String rAddress;
    private String rGender;
    private String rIdno;
    private String rName;
    private LinearLayout takePhoto;
    private boolean twoUpload;
    private int type;
    private LinearLayout takeView, msgView;
    private View view;
    private TextView okBtn, realName, idno, tishi;
    private ImageView take1, take2;
    private UploadSubmitIdcardBean newModel = new UploadSubmitIdcardBean();
    private boolean modifiable;
    private int btnType;
    private AutonymRequest api;
    private String pathFront;
    private String pathBack;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.autonym_activity);
        baseInitView(this, "AutonymActivity", Const.ViewType.ACTIVITY);
        initView();

    }


    private void checkCameraPermission(final int type) {

        checkPermission(new PermissionActivity.CheckPermListener() {
            @Override
            public void superPermission() {
                if (type == 1) {
                    btnId = 1;
                    startActivity(DEFAULT_NAME1);
                } else if (type == 2) {
                    btnId = 2;
                    startActivity(DEFAULT_NAME2);
                }
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    private boolean checkPhoto() {
        if (!this.isTakeOne) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.photo_one_is_empty), 0).show();
            return false;
        }
        if (!this.isTakeTwo) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.photo_two_is_empty), 0).show();
            return false;
        }
        return true;
    }

    /**
     * 上传身份证
     *
     * @param paramInt
     */
    private void getIdentity(int paramInt) {
        String str = "";
        if (paramInt == 0) {
            if ((BitmapDrawable) frontIv.getDrawable() == null) {
                ToastUtil.makeText(this, "身份证正面加载失败，请重新上传", Toast.LENGTH_SHORT).show();
                return;
            }
//            str = ImageUtil.File2byte(pathFront);
            str = ImageUtil.Bitmap2StrByBase64(((BitmapDrawable) frontIv.getDrawable()).getBitmap());
        }

        if (paramInt == 1) {
            if ((BitmapDrawable) backIv.getDrawable() == null) {
                ToastUtil.makeText(this, "身份证反面加载失败，请重新上传", Toast.LENGTH_SHORT).show();
                return;
            }
//            if (TextUtils.isEmpty(pathBack)) {
//                ToastUtil.makeText(this, "身份证反面加载失败，请重新上传", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            str = ImageUtil.File2byte(pathBack);
            str = ImageUtil.Bitmap2StrByBase64(((BitmapDrawable) backIv.getDrawable()).getBitmap());
        }
        api.getIdentityInfo(paramInt, str);
    }

    private void initView() {
        api = AutonymRequest.create();
        api.attachView(this);


        setTitleText(getResources().getString(R.string.shiming));
        setBackIntent();
        this.take1 = (ImageView) findViewById(R.id.take1);
        this.take2 = (ImageView) findViewById(R.id.take2);
        this.frontIv = ((ImageView) findViewById(R.id.front_iv));
        this.backIv = ((ImageView) findViewById(R.id.back_iv));
        this.loading = ((CircularProgress) findViewById(R.id.progressBar));
        this.takePhoto = ((LinearLayout) findViewById(R.id.take_photo));
        takeView = ((LinearLayout) findViewById(R.id.take_view1));
        msgView = ((LinearLayout) findViewById(R.id.msg_view1));
        realName = (TextView) findViewById(R.id.real_name);
        idno = (TextView) findViewById(R.id.idcard);
        tishi = (TextView) findViewById(R.id.tishi);
        this.frontIv.setOnClickListener(this);
        this.backIv.setOnClickListener(this);
        okBtn = (TextView) findViewById(R.id.ok);
        okBtn.setOnClickListener(this);

        try {
            btnType = getIntent().getIntExtra("type", 0);
            String name = getIntent().getStringExtra("real_name");
            String idcard = getIntent().getStringExtra("idcard");
            if (!TextUtils.isEmpty(name) || !TextUtils.isEmpty(idcard)) {
                realName.setText(name);
                idno.setText(idcard);
                takeView.setVisibility(View.GONE);
                msgView.setVisibility(View.VISIBLE);
                tishi.setText(getResources().getString(R.string.you_pass_autonym));
            } else {
                takeView.setVisibility(View.VISIBLE);
                msgView.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void showIdCardDialog() {
        oneUpload = false;
        twoUpload = false;
        Dialog.showIdcardDialog(this, modifiable, this.rName, this.rGender, this.rIdno, this.rAddress, getResources().getString(R.string.confirm), new Dialog.IdCardClickListener() {
            public void cancel() {
            }

            public void confirm(String name, String address) {
                try {
                    if (!TextUtils.isEmpty(name))
                        newModel.setName(URLEncoder.encode(name, "utf-8"));
                    if (!TextUtils.isEmpty(address))
                        newModel.setAddress(URLEncoder.encode(address, "utf-8"));

                    getSubmitidCard(rName, rIdno);

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 上传照片
     */
    private void getSubmitidCard(final String name, final String idcard) {
        api.getSubmitidCard(name, idcard, newModel);
    }


    /**
     * 是否显示加载框
     *
     * @param b
     */
    private void showLoading(boolean b) {
        if (loading != null) {
            if (b) {
                okBtn.setEnabled(false);
                frontIv.setEnabled(false);
                backIv.setEnabled(false);
                loading.setVisibility(View.VISIBLE);
            } else {
                okBtn.setEnabled(true);
                frontIv.setEnabled(true);
                backIv.setEnabled(true);
                loading.setVisibility(View.GONE);
            }
        }
    }

    private void startActivity(String paramString) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
////            大于21使用Camera2
//            Intent localIntent = new Intent(this, Camera2Activity.class);
//            localIntent.putExtra("path", "/sdcard/pictures");
//            localIntent.putExtra("name", paramString);
//            localIntent.putExtra("type", "idcard");
//            startActivityForResult(localIntent, 100);
//        } else {
//            小于21使用Camera
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
//        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
//                Bundle extras = data.getExtras();
//                String path = extras.getString("path");
//                String type = extras.getString("type");
//                Toast.makeText(getActivity(), "path:" + path + " type:" + type, Toast.LENGTH_LONG).show();
//                File file = new File(path);
//                FileInputStream inStream = null;
                try {
//                    byte[] bis = data.getByteArrayExtra("bitmap");
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
//                    inStream = new FileInputStream(file);
//                    Bitmap bitmap = BitmapFactory.decodeStream(inStream);
//                    inStream.close();
                    if (btnId == 1) {
                        isTakeOne = true;
                        take1.setVisibility(View.GONE);
//                        pathFront = path;
//                        Glide.with(this).load(file).asBitmap().into(frontIv);
//                        frontIv.setImageBitmap(bitmap);
                        if (IdCardBitmap.bitmap != null) {
                            frontIv.setImageBitmap(IdCardBitmap.bitmap);
                        }

                    } else if (btnId == 2) {
                        isTakeTwo = true;
                        take2.setVisibility(View.GONE);
//                        pathBack = path;
//                        Glide.with(this).load(file).asBitmap().into(backIv);
//                        backIv.setImageBitmap(bitmap);
                        if (IdCardBitmap.bitmap != null) {
                            backIv.setImageBitmap(IdCardBitmap.bitmap);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void onClick(View paramView) {
        switch (paramView.getId()) {
            default:
            case R.id.ok:
                if (checkPhoto())
                    okBtn.setEnabled(false);
                getIdentity(0);
                break;
            case R.id.front_iv:
                type = 1;
                checkCameraPermission(1);
                break;
            case R.id.back_iv:
                type = 2;
                checkCameraPermission(2);
                break;
        }
    }

    public void onDestroy() {
        super.onDestroy();
        api.detachView();
        api = null;
        if (IdCardBitmap.bitmap != null && !IdCardBitmap.bitmap.isRecycled()) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }
    }


    /**
     * 检查身份证信息完整性
     *
     * @return
     */
    private boolean checkIdCard(int id) {
        if (id == 0)
            if (TextUtils.isEmpty(newModel.getName()) || TextUtils.isEmpty(newModel.getGendor()) || TextUtils.isEmpty(newModel.getNation()) || TextUtils.isEmpty(newModel.getBirthday()) || TextUtils.isEmpty(newModel.getAddress()) || TextUtils.isEmpty(newModel.getIdno()) || TextUtils.isEmpty(newModel.getFront_image())) {
                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_front), Toast.LENGTH_SHORT).show();
                oneUpload = false;
                twoUpload = false;
                return false;
            }
        if (id == 1)
            if (TextUtils.isEmpty(newModel.getIssue_by()) || TextUtils.isEmpty(newModel.getValid_start()) || TextUtils.isEmpty(newModel.getValid_end()) || TextUtils.isEmpty(newModel.getBack_image())) {
                ToastUtil.makeText(this, getResources().getString(R.string.not_discern_back), Toast.LENGTH_SHORT).show();
                oneUpload = false;
                twoUpload = false;
                return false;
            }

        return true;
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        showLoading(false);
        okBtn.setEnabled(true);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    @Override
    public void getSubmitidCardSuccess(String name, String idcard, ResponseModel item) {
        ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.upload_success), Toast.LENGTH_SHORT).show();
        PreferenceUtils.putString(this, "idcardpassed", "1");
        if (btnType == 1) {
            Util.startActivity(AutonymActivity.this, V3BankListActivity.class);
        } else {
            realName.setText(name);
            idno.setText(idcard);
            takePhoto.setVisibility(View.GONE);
            msgView.setVisibility(View.VISIBLE);
            okBtn.setVisibility(View.GONE);
            tishi.setText(getResources().getString(R.string.you_pass_autonym));
        }
    }

    @Override
    public void getIdentityInfoSuccess(IdentityModel model) {
        if (model.getModifiable() == 1)
            modifiable = true;
        else modifiable = false;
        if (!TextUtils.isEmpty(model.getFront_image()))
            oneUpload = true;

        if (!TextUtils.isEmpty(model.getBack_image()))
            twoUpload = true;

        if (!twoUpload) {
            rName = model.getName();
            rGender = model.getGendor();
            rIdno = model.getIdno();
            rAddress = model.getAddress();

            try {
                if (!TextUtils.isEmpty(rName))
                    newModel.setName(URLEncoder.encode(rName, "utf-8"));
                if (!TextUtils.isEmpty(rGender))
                    newModel.setGendor(URLEncoder.encode(rGender, "utf-8"));
                newModel.setIdno(rIdno);
                if (!TextUtils.isEmpty(rAddress))
                    newModel.setAddress(URLEncoder.encode(rAddress, "utf-8"));
                if (!TextUtils.isEmpty(model.getNation()))
                    newModel.setNation(URLEncoder.encode(model.getNation(), "utf-8"));
                if (!TextUtils.isEmpty(model.getBirthday()))
                    newModel.setBirthday(URLEncoder.encode(model.getBirthday(), "utf-8"));
                newModel.setFront_image(model.getFront_image());

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //检查身份证信息完整性
            if (checkIdCard(0))
                getIdentity(1);

        } else {
            try {
                if (!TextUtils.isEmpty(model.getIssue_by()))
                    newModel.setIssue_by(URLEncoder.encode(model.getIssue_by(), "utf-8"));
                newModel.setBack_image(model.getBack_image());
                newModel.setValid_start(model.getValid_start());
                newModel.setValid_end(model.getValid_end());

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //检查身份证信息完整性
            if (checkIdCard(1))
                showIdCardDialog();
        }
        if (!TextUtils.isEmpty(model.getMsg()))
            ToastUtil.makeText(getApplicationContext(), model.getMsg(), 0).show();
    }

    @Override
    public void getIdentityInfoFail(String result) {
        oneUpload = false;
        twoUpload = false;
        if (!TextUtils.isEmpty(result))
            ToastUtil.makeText(getApplicationContext(), result, 0).show();
    }
}
